package org.dt.common.sequence;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;

import org.dt.common.sequence.config.SeqHolderConfig;
import org.dt.common.sequence.config.SeqHolderSpec;
import org.dt.common.sequence.config.SeqHolderType;

@Slf4j
public class SequenceHolderFactory {

    private Map<String, SequenceHolder> holders = new HashMap<>();

    public SequenceHolderFactory(SeqHolderConfig seqHolderConfig, BaseDelegator delegator, Executor taskExecutor) {
        init(seqHolderConfig, delegator, taskExecutor);
    }

    public SequenceHolder sequenceHolder(String biz) {
        return holders.get(biz);
    }

    private void init(SeqHolderConfig seqHolderConfig, BaseDelegator delegator, Executor taskExecutor) {
        for (String biz : seqHolderConfig.getTypes().keySet()) {
            SeqHolderType type          = seqHolderConfig.getTypes().get(biz);
            SeqHolderSpec seqHolderSpec = seqHolderConfig.getSpecs().get(biz);
            if (seqHolderSpec == null) {
                throw new IllegalArgumentException(SeqHolderSpec.class.getSimpleName() + " of " + biz + " not exists.");
            }

            SequenceHolder sequenceHolder;
            switch (type) {
                case DEFAULT:
                case HEAD_SPINNING:
                    sequenceHolder = new HeadSpinningSequenceHolder(biz, seqHolderSpec, delegator, taskExecutor);
                    break;
                case GREEDY:
                    sequenceHolder = new GreedyPollSequenceHolder(biz, seqHolderSpec, delegator, taskExecutor);
                    log.warn("GreedyPollSequenceHolder is deprecated");
                    break;
                default:
                    throw new IllegalArgumentException();
            }

            holders.put(biz, sequenceHolder);
        }
        log.info("发现 {}个biz项。详情：{}", holders.size(), seqHolderConfig);
    }

}
